import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'base_state.dart';

/// 基础通知器
abstract class BaseNotifier<T> extends StateNotifier<BaseState<T>> {
  BaseNotifier() : super(const BaseState());

  /// 设置闲置状态
  void setIdle() {
    state = state.copyWith(pageState: PageState.idle);
  }

  /// 设置加载状态
  void setLoading() {
    state = state.copyWith(pageState: PageState.loading);
  }

  /// 设置成功状态
  void setSuccess(T? data) {
    state = state.copyWith(
        pageState: PageState.success, data: data, clearErrorMessage: true);
  }

  /// 设置空数据状态
  void setEmpty() {
    state = state.copyWith(
      pageState: PageState.empty,
      clearData: true,
      clearErrorMessage: true,
    );
  }

  /// 设置错误状态
  void setError(String message, [dynamic exception]) {
    state = state.copyWith(
      pageState: PageState.error,
      errorMessage: message,
      exception: exception,
    );
  }
}

/// 基础状态管理器
abstract class BaseLoadNotifier<T> extends BaseNotifier<T> {
  BaseLoadNotifier();

  /// 初始化数据
  Future<void> initData() async {
    setLoading();

    try {
      final data = await loadData();

      if (data == null || (data is List && data.isEmpty)) {
        setEmpty();
      } else {
        setSuccess(data);
      }

      if (data == null || (data is List && data.isEmpty)) {
        setEmpty();
      } else {
        setSuccess(data);
      }
    } catch (e) {
      setError(e.toString(), e is Exception ? e : Exception(e.toString()));
    }
  }

  /// 重试操作
  Future<void> retry() async {
    if (state.pageState == PageState.error) {
      await loadData();
    }
  }

  /// 重置状态
  void reset() {
    state = const BaseState();
  }

  /// 获取数据
  Future<T?> loadData();
}
